 #define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int dx[4] = { 0, 0, -1, 1 };
    int dy[4] = { 1, -1, 0 ,0 };
    int vis[10][10];
    int fresh;
    int orangesRotting(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int ret = 0;
        fresh = 0;//记录新鲜橘子
        queue<pair<int, int>> q;
        memset(vis, -1, sizeof(vis));//记录每个节点中橘子的腐烂时间

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 2)
                {
                    q.push({ i, j });
                    vis[i][j] = 0;
                }
                else if (grid[i][j] == 1) fresh++;
            }
        }

        if (q.empty()) ret = 0;

        while (!q.empty())
        {
            auto [a, b] = q.front();
            q.pop();

            for (int k = 0; k < 4; k++)
            {
                int x = a + dx[k], y = b + dy[k];
                if (x < 0 || x >= m || y < 0 || y >= n || ~vis[x][y] || !grid[x][y]) continue;

                vis[x][y] = vis[a][b] + 1;
                q.push({ x, y });

                if (grid[x][y] == 1)
                {
                    --fresh;
                    ret = vis[x][y];
                    //没有新鲜橘子，则直接返回
                    if (!fresh) break;
                }
            }
        }
        return fresh ? -1 : ret;
    }
};